<template>
  <div class="ek-list-tree" v-loading="loading">
    <ekTree
      ref="treeRef"
      :data="treeData"
      :defaultProps="defaultConfig.defaultProps"
      :expandOnClickNode="false"
      :defaultExpandAll="defaultConfig.config.defaultExpandAll"
      :lazy="defaultConfig.config.lazy"
      :nodeKey="defaultConfig.config.nodeKey"
      :placeholder="defaultConfig.config.placeholder"
      :load="handleLoad"
      @node-click="handleNodeClick"
    >
    </ekTree>
  </div>
</template>

<script setup>
import {
  defineComponent,
  onMounted,
  getCurrentInstance,
  reactive,
  ref,
} from "vue";

import ekTree from "@/components/business/ekTree/index.vue";
import { arrayToTree } from "@/utils/common";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http } = globalProperties;
const store = useStore();
const router = useRouter();

const props = defineProps({
  // 配置
  config: {
    type: Object,
    default: () => {},
  },
});

let defaultConfig = {
  defaultProps: {
    children: "children",
    label: "label",
    isLeaf: "leaf",
    disabled: "disabled",
    class: "class",
  },
  config: {
    lazy: false,
    defaultExpandAll: false,
    nodeKey: "id",
    placeholder: '请输入过滤条件'
  },
  ...props.config,
};
const emit = defineEmits(["node-click"]);

let loading = ref(null);
let modelCode = props.config.modelCode;
let url = props.config.url || `/business/basis/getTree?modelCode=${modelCode}`;
let fieldMapping = defaultConfig.fieldMapping;
let treeData = ref([
  {
    id: 'all',
    label: '全部',
    leaf: false,
    children: []
  }
]);

function init(){
    if(!defaultConfig.config.lazy){
      fetchData(); 
    }
}
function fetchData() {
   loading.value = true;
    $http
    .get(url)
    .then((res) => {
      console.log(res);
      let tree = res.data;
      if (tree.length) {
        for (let i in fieldMapping) {
          let val = fieldMapping[i];
          for (let j in tree) {
            tree[j][i] = tree[j][val];
          }
        }
      }
     
      treeData.value[0].children = arrayToTree(tree);
      loading.value = false;
    }).catch(()=>{
      loading.value = false;
    });
}
function handleLoad(node, resolve, reject) {
    $http
    .post( url,
      {
      type: "lazy",
      parentId: node.data.id,
    })
    .then((res) => {
      console.log(res);
      let tree = res.data;
      if (tree.length) {
        for (let i in fieldMapping) {
          let val = fieldMapping[i];
          for (let j in tree) {
            tree[j][i] = tree[j][val];
          }
        }
      }
      resolve(tree);
    });
}
function handleNodeClick(node) {
    emit('node-click', node)
}
init();
</script>

<style scoped lang="scss"></style>
